package com.defysoft.waukidsbus.end;

import java.util.ArrayList;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukidsbus.BaseActivity;
import com.defysoft.waukidsbus.Data_Type.BC_BACKBUS;
import com.defysoft.waukidsbus.Data_Type.BC_GOBUS;
import com.defysoft.waukidsbus.JsonParser;
import com.defysoft.waukidsbus.R;
import com.defysoft.waukidsbus.start.Start_ScanMode;

public class End_Select extends BaseActivity {

	Toolbar toolbar;
	GridView listView;
	ArrayList<BC_BACKBUS> list;
	final int SUCCESS = 10;
	final int FAIR = 9;
	EditText et;
	EditText et2;
	StartAdapter startAdapter;
	private SharedPreferences login_code;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_end__select);
		setStartData();
	}

	@Override
	public void setStartData() {
		// TODO Auto-generated method stub
		super.setStartData();
		login_code = getSharedPreferences("login_code", MODE_PRIVATE);
		listView = (GridView) findViewById(R.id.END_SELECT_LIST);
		toolbar = (Toolbar) findViewById(R.id.END_SELECT_TOOL);
		et = (EditText) findViewById(R.id.SET_END_SCANTIME);
		et2 = (EditText) findViewById(R.id.SET_END_SCANCOUNT);
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		try {
			if (login_code.getString("scantime", null) != null) {
				int times = Integer.parseInt(login_code.getString("scantime",
						null));
				et.setText(times + "");
			}
		} catch (Exception e) {
			et.setText("10");
		}
		try {
			if (login_code.getString("scancount", null) != null) {
				int times = Integer.parseInt(login_code.getString("scancount",
						null));
				et2.setText(times + "");
			}
		} catch (Exception e) {
			et2.setText("3");
		}
		startNetwork(1);
	}

	@Override
	public void startThread(int choice) {
		// TODO Auto-generated method stub
		super.startThread(choice);
		firstThread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				mainThread();
			}
		});
		firstThread.start();
	}

	@Override
	protected void handlingMessage(Message _message) {
		// TODO Auto-generated method stub
		super.handlingMessage(_message);
		switch (_message.what) {
		case CATCH_EXCEPTION:
			endDIal();
			if (firstThread == null) {
				firstThread.interrupt();
			}
			showPopup("네트워크오류", "네트워크 실패", 0);
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			break;
		case FAIR:
			endDIal();
			if (firstThread == null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT)
					.show();
			break;
		case SUCCESS:
			endDIal();
			if (firstThread == null) {
				firstThread.interrupt();
			}
			list = JsonParser.AttendEndSelectMember((String) _message.obj);
			startAdapter = new StartAdapter();
			listView.setAdapter(startAdapter);
			if (list.size() == 1) {

				listView.setNumColumns(1);
				listView.setLayoutParams(new LinearLayout.LayoutParams(
						(listView.getWidth() / 2), listView.getHeight()));
			} else if (list.size() == 2) {

				listView.setNumColumns(2);
			} else if (list.size() >= 3) {

				listView.setNumColumns(3);
			}
			break;
		}
	}

	protected void mainThread() {
		// TODO Auto-generated method stub
		String msg = "";
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(
					HTTP_SELECT_END,
					"code=" + login_code.getString("sch_code", null)));
			if (jsonObject.getBoolean("success")) {
				msg = jsonObject.getString("payload");
				onNetworkCallback(SUCCESS, msg);
			} else {
				onNetworkCallback(FAIR, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString());
		}
		;
	}

	class StartAdapter extends ArrayAdapter<String> {

		public StartAdapter() {
			super(End_Select.this, 0);
			// TODO Auto-generated constructor stub
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			final int pos = position;
			StartHolder startHolder;
			if (convertView == null) {
				convertView = getLayoutInflater().inflate(
						R.layout.start_select_row, null);
				int width = ((listView.getWidth()) / 3);
				int height = ((listView.getWidth()) / 3);

				(convertView.findViewById(R.id.START_SELECT_LL))
						.setLayoutParams(new LinearLayout.LayoutParams(
								LayoutParams.MATCH_PARENT, (int) ((listView
										.getHeight()) * 0.7)));
				startHolder = new StartHolder();
				startHolder.textView = (TextView) convertView
						.findViewById(R.id.START_SELECT_ROW);
				convertView.setTag(startHolder);
			} else {
				startHolder = (StartHolder) convertView.getTag();
			}
			startHolder.textView.setText(list.get(position).Bac_Name);
			convertView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					AlertDialog.Builder builder = new AlertDialog.Builder(
							End_Select.this);
					builder.setMessage(
							list.get(pos).Bac_Name
									+ " 버스를 선택하셨습니다.\n운행이 시작되면 탑승한 원생의 부모님께 메시지가 전송 됩니다.")
							.setCancelable(false)
							.setPositiveButton("운행시작",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											login_code
													.edit()
													.putString(
															"scantime",
															et.getText()
																	.toString())
													.putString(
															"scancount",
															et2.getText()
																	.toString())
													.commit();
											startActivity(new Intent(
													End_Select.this,
													End_ScanMode.class)
													.putExtra(
															"code",
															list.get(pos).PK_Bac_Code
																	+ "")
													.putExtra(
															"second",
															et.getText()
																	.toString())
													.putExtra(
															"count",
															et2.getText()
																	.toString())

													.putExtra(
															"Gob_Name",
															list.get(pos).Bac_Name)// 버스이름.
											);
										}
									})
							.setNegativeButton("취소",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											dialog.cancel();
										}
									});
					AlertDialog alert = builder.create();
					alert.show();

				}
			});
			return convertView;
		}
	}

	class StartHolder {
		TextView textView;
	}

}
